package Top200;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangmin
 * @create 2022-02-22 11:13
 * 排序+回溯
 */
public class permuteUnique47 {
    boolean[] visited;
    List<List<Integer>> res=new LinkedList<>();
    void backtrack(int[] nums,LinkedList<Integer> path){
        if (path.size()==nums.length){
            res.add(new LinkedList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i]||(i>0&&nums[i]==nums[i-1]&&!visited[i-1])){
                continue;
            }
            path.addLast(nums[i]);
            visited[i]=true;
            backtrack(nums,path);
            visited[i]=false;
            path.pollLast();
        }
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        visited=new boolean[nums.length];
        backtrack(nums,new LinkedList<>());
        return res;
    }
}
